#pragma once

#include <poll.h>
#include <unistd.h>
#include <fcntl.h>
#include <unordered_map>
#include <memory>
#include <vector>

class users
{
public:
    users(size_t uid)
        :_uid(uid)
    {}

    size_t use_uid() {return _uid;}
    char *get_buffer() {return _buffer;}
    int get_buffer_size() {return strlen(_buffer);};
    void set_buffer_empty() {_buffer[0] = 0;}
protected:
    size_t _uid;
    char _buffer[1024] = {0};
};


typedef std::shared_ptr<users> users_t;
class users_manamger
{
public:
    void create_user( std::vector<pollfd> &pollfd_vec,int sockfd)
    {
        // int old_option = fcntl(sockfd,F_GETFL);
        // int new_option = old_option | O_NONBLOCK;
        // fcntl(sockfd,F_SETFL,new_option);
        users_t users_ptr(new users(_uid));
        _uid_users.insert(std::make_pair(_uid,users_ptr));
        pollfd pd;
        pd.fd = sockfd;
        pd.events = POLLIN | POLLERR | POLLRDHUP;
        pd.revents = 0;
        // 将pollfd对象放入容器当中
        pollfd_vec.push_back(pd);
        _sockfd_uid.insert(std::make_pair(sockfd,_uid));
        ++_uid;
    }

    users_t get_by_uid(size_t uid)
    {
        auto it = _uid_users.find(uid);
        if(it == _uid_users.end())
        {
            return users_t();
        }
        return it->second;
    }

    size_t get_uid_by_sockfd(int sockfd)
    {
        auto it = _sockfd_uid.find(sockfd);
        if(it == _sockfd_uid.end())
        {
            return -1;
        }
        return it->second;
    }
protected:
    size_t _uid = 1;// 用于分配
    std::unordered_map<size_t,users_t> _uid_users;
    std::unordered_map<int,size_t> _sockfd_uid;
};